/**
* Author: fulishang
* Create Time  : 2016年8月5日,上午12:36:28
* Modify Time :
* Desc  : 
*/
package com.sam.si.file.transformer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.springframework.integration.file.transformer.AbstractFilePayloadTransformer;
import org.springframework.util.Assert;

public class FileTransformer extends AbstractFilePayloadTransformer<String> {

	private static final Logger LOGGER = Logger.getLogger(FileTransformer.class);

	private volatile Charset charset = Charset.defaultCharset();

	/**
	 * Set the charset name to use when copying the File to a String.
	 *
	 * @param charset
	 *            The charset.
	 */
	public void setCharset(String charset) {
		Assert.notNull(charset, "charset must not be null");
		Assert.isTrue(Charset.isSupported(charset), "Charset '" + charset + "' is not supported.");
		this.charset = Charset.forName(charset);
	}

	@Override
	protected String transformFile(File file) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), this.charset));
		// filter the header and footer
		StringBuilder sb = new StringBuilder();
		for (String line = br.readLine(); line != null; line = br.readLine()) {
			if (line.startsWith("HEADER") || line.startsWith("FOOTER")) {
				LOGGER.info("Lines to be ignored --> " + line);
				continue;
			} else {
				sb.append(line + "\r\n");
			}
		}
		br.close();
		return sb.toString();
	}

}
